package com.bodacn.keypoint;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.bodacn.keypoint.adapter.TaskTopAdapter;
import com.bodacn.keypoint.bean.TaskTopBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ProductPlanActivity extends AppCompatActivity {

    TaskTopAdapter topAdapter;
    List<TaskTopBean> topBeanList = new ArrayList<>();
    String SearchStartData = "", SearchEndData = "", PartName = "", DepartNo = "", UserNo = "";
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.edt_StartDate)
    EditText edtStartDate;
    @BindView(R.id.edt_EndDate)
    EditText edtEndDate;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.btn_Return)
    Button btnReturn;
    @BindView(R.id.txt_HintInfo)
    TextView txtHintInfo;
    @BindView(R.id.tv_pdrq)
    TextView tvPdrq;
    @BindView(R.id.tv_zdh)
    TextView tvZdh;
    @BindView(R.id.tv_kh)
    TextView tvKh;
    @BindView(R.id.tv_color)
    TextView tvColor;
    @BindView(R.id.tv_cm)
    TextView tvCm;
    @BindView(R.id.tv_dds)
    TextView tvDds;
    @BindView(R.id.tv_drpcs)
    TextView tvDrpcs;
    @BindView(R.id.tv_jy)
    TextView tvJy;
    @BindView(R.id.tv_pcts)
    TextView tvPcts;
    @BindView(R.id.tv_fzr)
    TextView tvFzr;
    @BindView(R.id.tv_sxrq)
    TextView tvSxrq;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.gr_top)
    ListView grTop;

    private JSONArray todayJsonArray;
    public static final int MSG_Today = 101;
    public static final int MSG_ERRMSG = 103;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_plan);
        ButterKnife.bind(this);

        topAdapter = new TaskTopAdapter(this, topBeanList);
        grTop.setAdapter(topAdapter);


        Bundle paramBundle = this.getIntent().getExtras();
        PartName = paramBundle.getString("PartName");
        DepartNo = paramBundle.getString("CurDepartNo");
        UserNo = paramBundle.getString("UserNo");
        Date curDate = new Date(System.currentTimeMillis());
        String EndDateStr = (String) DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime()));
        edtStartDate.setText(EndDateStr);
        edtEndDate.setText(EndDateStr);

        searchBarcodeData("TodayPlan", MSG_Today);

    }

    //扫描
    private void searchBarcodeData(String operType, int msg) {
        SearchStartData = edtStartDate.getText().toString().trim();
        SearchEndData = edtEndDate.getText().toString().trim();
        //执行SQL过程
        String SqlComm = "Exec AGV_TaskList @OPERTYPE='" + operType + "'" +
                ",@SearchStartData='" + SearchStartData + "', @SearchEndData='" + SearchEndData +
                "',@PartName='" + PartName + "',@DepartNo='" + DepartNo + "',@UserNo='" + UserNo + "'";
        ReadSQLData(SqlComm, msg);
    }


    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm, final int msg) {
        Log.e("过程", SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray jsonArray = ToolUtil.QuerySQL2JSON(SQLComm);
                    Log.e("结果", "结果" + jsonArray);
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        if (jsonArray.optJSONObject(0).has("OPERTYPE") == true) {
                            //日生产计划单
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("TodayPlan")) {
                                todayJsonArray = jsonArray;
                                Message msg = new Message();
                                msg.what = MSG_Today;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            Message message = new Message();
                            message.what = MSG_ERRMSG;
                            Bundle bundle = new Bundle();
                            bundle.putString("Hint", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            message.setData(bundle);
                            fragmentHandler.sendMessage(message);
                        }

                    } else {
                        Message message = new Message();
                        message.what = msg;
                        Bundle bundle = new Bundle();
                        bundle.putString("Hint", "未返回任何数据!");
                        message.setData(bundle);
                        fragmentHandler.removeMessages(message.what);
                        fragmentHandler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = MSG_ERRMSG;
                    Bundle bundle = new Bundle();
                    bundle.putString("Hint", e.getMessage().toString());
                    message.setData(bundle);
                    fragmentHandler.sendMessage(message);
                }

            }

        };
        new Thread(run).start();

    }

    @SuppressLint("HandlerLeak")
    public final Handler fragmentHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null) {
                int msgId = msg.what;
                switch (msgId) {
                    //日生产计划单
                    case MSG_Today:
                        if (todayJsonArray != null && todayJsonArray.length() > 0) {
                            List<TaskTopBean> detailBeans = new Gson().fromJson(String.valueOf(todayJsonArray), new TypeToken<List<TaskTopBean>>() {
                            }.getType());
                            topBeanList.clear();
                            topBeanList.addAll(detailBeans);
                            topAdapter.notifyDataSetChanged();
                        } else {
                            topBeanList.clear();
                            topAdapter.notifyDataSetChanged();
                        }
                        break;

                    //报错
                    case MSG_ERRMSG:
                        Bundle bundle1 = msg.getData();
                        String resultMsg = bundle1.getString("Hint");
                        AlertDialog alertDialog = new AlertDialog.Builder(ProductPlanActivity.this)
                                .setTitle("系统提示").setMessage(resultMsg)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                }).create();
                        alertDialog.show();
                        break;
                    default:
                        break;
                }
            }
        }
    };


    @OnClick({R.id.edt_StartDate, R.id.edt_EndDate, R.id.btn_search, R.id.btn_Return})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.edt_StartDate:
                final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(view.getContext(), null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog.setButton(DialogInterface.BUTTON_POSITIVE, "完成", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year, month, day);
                        edtStartDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle("选择查询起始日期");
                mDialog.show();
                break;
            case R.id.edt_EndDate:
                final Calendar calendara = Calendar.getInstance();
                final DatePickerDialog mDialoga = new DatePickerDialog(view.getContext(), null, calendara.get(Calendar.YEAR), calendara.get(Calendar.MONTH), calendara.get(Calendar.DAY_OF_MONTH));
                mDialoga.setButton(DialogInterface.BUTTON_POSITIVE, "完成", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialoga.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendara.set(year, month, day);
                        edtEndDate.setText(DateFormat.format("yyyy-MM-dd", calendara));
                    }
                });
                mDialoga.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialoga.setTitle("选择查询截止日期");
                mDialoga.show();
                break;
            case R.id.btn_search:
                searchBarcodeData("TodayPlan", MSG_Today);
                break;
            case R.id.btn_Return:
                finish();
                break;
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}
